package com.tencreat.common.service.impl;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tencreat.common.core.enums.ImSessionType;
import com.tencreat.common.core.exception.CustomException;
import com.tencreat.common.entity.ImMessage;
import com.tencreat.common.entity.ImSession;
import com.tencreat.common.entity.ImUser;
import com.tencreat.common.entity.ImUserSession;
import com.tencreat.common.entity.vo.UserAddVo;
import com.tencreat.common.entity.vo.UserSessionVo;
import com.tencreat.common.mapper.ImSessionMapper;
import com.tencreat.common.service.ImSessionService;
import com.tencreat.common.service.ImUserSessionService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ImSessionServiceImpl extends ServiceImpl<ImSessionMapper, ImSession> implements ImSessionService {

    @Autowired
    ImUserSessionService userSessionService;

    @Override
    public Page<UserSessionVo> sessionList(Page<UserSessionVo> page, Long id) {
        //TODO lastACK 群聊需要单独处理
        return baseMapper.sessionList(page, id);
    }

    @Override
    public Page<ImMessage> chatHistory(Page<ImMessage> page, Long id) {
        return baseMapper.chatHistory(page, id);
    }

    @Override
    @Transactional
    public UserSessionVo newSession(ImUser fromUser, ImUser toUser) {
        if(fromUser.getId() == toUser.getId()){
            throw new CustomException("创建会话失败,不能和自己创建会话");
        }
        UserSessionVo userSessionVo = new UserSessionVo();
        //添加一个和管理员的会话
        ImSession imSession = new ImSession();
        imSession.setUserId(toUser.getId()); // 对方ID
        imSession.setType(ImSessionType.SINGLE);
        imSession.setCreateUser(fromUser.getId());
        save(imSession);

        // 添加两个user_session
        ImUserSession fromSession = new ImUserSession();
        fromSession.setUserId(fromUser.getId());
        fromSession.setSessionId(imSession.getId());
        fromSession.setName(toUser.getUsername());
        fromSession.setAvatar(toUser.getAvatar());
        fromSession.setSessionType(ImSessionType.SINGLE);
        fromSession.setToId(toUser.getId());
        userSessionService.save(fromSession);

        ImUserSession toSession = new ImUserSession();;
        toSession.setUserId(toUser.getId());
        toSession.setSessionId(imSession.getId());
        toSession.setName(fromUser.getUsername());
        toSession.setAvatar(fromUser.getAvatar());
        toSession.setSessionType(ImSessionType.SINGLE);
        toSession.setToId(fromUser.getId());
        userSessionService.save(toSession);

        BeanUtils.copyProperties(fromSession, userSessionVo);
        userSessionVo.setFromAvatar(fromUser.getAvatar());
        return userSessionVo;
    }
}
